function _request(method = 'POST', {
	host = '',
	url = '',
	params = {},
	config = {}
}) {
	return new Promise((resolve, reject) => {
		const userId = Vue.prototype.$storage.getUserId();
		if (!userId) {
			_show_error('登录失效,请重新登录');
			uni.reLaunch({
				url: '/pages/login/login'
			});
			return;
		}

		params &&
			Object.keys(params).map(key => {
				if (params[key] === undefined) {
					params[key] = null;
				}
			});
		// console.log(params);
		let path = `${host}${url}`;
		const _pathParams = `tenantId=${tenantId}&userId=${userId}`;
		if (path.indexOf('?') > -1) {
			path = `${path}&${_pathParams}`;
		} else {
			path = `${path}?${_pathParams}`;
		}
		// console.log(path);
		uni.request({
			url: path,
			method,
			data: params,
			header: {
				'Content-Type': 'application/json;charset=utf-8'
			},
			success: res => {
				// console.log('success', res);
				// 异常
				if (res.statusCode !== 200) {
					if (!config.hideMsg) _show_error(res.data.msg || res.errMsg);
					reject();
					return;
				}
				// 成功
				if (!res.data.code || res.data.code === '0') {
					resolve(res.data);
					return;
				}
				// 未登录
				if (res.data.code === '101') {
					_show_error('登录失效,请重新登录');
					uni.reLaunch({
						url: '/pages/login/login'
					});
					return;
				}
				// 失败
				if (!config.hideMsg) _show_error(res.data.msg);
				reject(res.data);
			},
			fail: error => {
				// console.log('error', error);
				if (!config.hideMsg) _show_error(error.errMsg);
				reject();
			}
		})
	})
}

function _show_error(message) {
	uni.showToast({
		title: message || '请求失败,请稍后重试',
		icon: 'none'
	})
}

const request = {
	get(host, url, params = {}, config = {}) {
		return _request('GET', {
			host,
			url,
			params,
			config
		});
	},
	post(host, url, params = {}, config = {}) {
		return _request('POST', {
			host,
			url,
			params,
			config
		});
	},
	put(host, url, params = {}, config = {}) {
		return _request('PUT', {
			host,
			url,
			params,
			config
		});
	}
};

export default request
